import threading

class DatabaseConnectorPool:
    """
    一个线程安全的多数据库连接池映射表。
    """
    def __init__(self):
        self._lock = threading.Lock()
        self._pool = {}  # 存储连接池的字典

    def get_or_create_connector(self, db_name, db_config,pool_size=5):
        with self._lock:
            if db_name in self._pool:
                return self._pool[db_name]

            # 创建新的连接池
            db_type = db_config.get("type", "mysql").lower()  # 默认数据库类型为 MySQL

            # 动态加载对应的 Connector 类
            if db_type == "mysql":
                init_args = {
                    key: db_config[key]
                    for key in ["host", "user", "password", "port", "database"]
                    if key in db_config
                }
                init_args["pool_size"] = db_config.get("pool_size", pool_size)
                from core.connectors.mysql_connector import MySQLConnector
                connector_class = MySQLConnector
            elif db_type == "postgresql":
                init_args = {
                    key: db_config[key]
                    for key in ["host", "port", "user", "password", "database"]
                    if key in db_config
                }
                init_args["pool_size"] = db_config.get("pool_size", pool_size)
                from core.connectors.postgresql_connector import PostgresqlConnector
                connector_class = PostgresqlConnector
            else:
                raise ValueError(f"不支持的数据库类型：{db_type}")

            connector = connector_class(**init_args)
            self._pool[db_name] = connector
            return connector

    def close_all(self):
        """
        关闭所有连接池，释放资源。
        """
        with self._lock:
            for db_name, connector in self._pool.items():
                try:
                    connector.close()
                except Exception as e:
                    print(f"关闭连接池 {db_name} 时出错: {e}")
            self._pool.clear()
